<script setup lang="ts">
import { frequencyType, freeType } from "@/config/dictionary";
import { zoonType } from "../components/config";
import { deepClone } from "@/utils";
import PrizePool from "./PrizePool.vue";
import RewardSelector from "./RewardSelector.vue";

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
});

const emits = defineEmits(["change", "update:modelValue"]),
  currencyList: Array<any> = inject("currencyList", []),
  activityReadonly = inject("activityReadonly");

const form = ref<any>({
    partType: 0,
    freeType: null,
    partTotalLimit: 0,
    lotteryTotalLimit: 0,
    lotteryLimitType: 0,
  }),
  prizeAreas = ref<Array<any>>([]),
  voteConfig = ref<any>({
    lotteryConfig: 1,
    voteRule: 1,
    voteChance: 1,
    duplicateChance: 1,
    rewardType: 0,
    rewardList: [{}],
  });

const formRef = ref(),
  poolRef = ref(),
  voteRef = ref();

const rules = {
  lotteryTotalNum: [
    { required: true, message: "请输入中奖总次数", trigger: "blur" },
  ],
  voteTime: [{ required: true, message: "请选择投票时间", trigger: "change" }],
  voteChance: [{ required: true, message: "请填写投票数", trigger: "blur" }],
  duplicateChance: [
    { required: true, message: "请填写投票数", trigger: "blur" },
  ],
};

const prizePoolType = computed(() => {
  return form.value.subType ? zoonType[form.value.subType].prizePool || [] : [];
});

const stopWatch = watch(
  () => props.modelValue,
  (val) => {
    nextTick(() => {
      stopWatch();
      formatData(val);
    });
  },
  {
    immediate: true,
  }
);

const formatData = (val: any) => {
  form.value = Object.assign({}, form.value, {
    ...val.pageArea,
    lotteryLimit:
      val.pageArea.lotteryLimit && typeof val.pageArea.lotteryLimit === "string"
        ? JSON.parse(val.pageArea.lotteryLimit)
        : [{ type: 1, limitNum: 1 }],
    lotteryLimitType: val.pageArea.lotteryLimit ? 1 : 0,
    partLimit: null,
  });
  voteConfig.value = Object.assign(
    {},
    voteConfig.value,
    val.voteConfigEntity || {
      pageFlag: form.value.pageFlag,
    }
  );
  voteConfig.value.voteTime = [
    voteConfig.value.voteStart,
    voteConfig.value.voteEnd,
  ];
  prizeAreas.value = val.prizeAreas || [];
  updateData();
};

const showPrizePool = computed(() => {
  // 开启抽奖，展示抽奖配置
  if (voteConfig.value.lotteryConfig == 1) {
    return true;
  }
  return false;
});

const quotePrize = computed(() => {
  let prize = voteConfig.value.rewardList.filter((item: any) => {
    if (item.rewardType === "PRIZE") {
      return true;
    }
    return false;
  });
  if (prize && prize.length > 0) {
    return prize.map((item: any) => {
      return {
        prizeId: item.prizeId,
        poolId: item.prizeArea,
        specId: item.prizeSpec,
      };
    });
  }
  return [];
});

// 添加奖池
const addPool = () => {
  poolRef.value.addPool();
};

// 添加奖池奖品
const addPoolPrize = (index: number) => {
  poolRef.value.addPrize(1, index);
};

const updateData = () => {
  emits("update:modelValue", {
    pageArea: form.value,
    prizeAreas: prizeAreas.value,
    voteConfigEntity: voteConfig.value,
  });
  emits("change");
};

const submit = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid: any, invalidFields: any) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        let voteConfigEntity = {};
        // 每人中奖限制
        if (detail.lotteryLimitType == 0) {
          detail.lotteryLimit = "";
        } else if (detail.lotteryLimit)
          detail.lotteryLimit = JSON.stringify(detail.lotteryLimit);

        // 无参与消耗自动填充免费次数
        detail.freeNum = null;
        detail.freeType = null;

        try {
          voteConfigEntity = await checkConfig();
          await poolRef.value.check(
            detail.lotteryLimitType === 1 || detail.lotteryTotalLimit === 1,
            true
          );
        } catch (e) {
          reject(e);
        }

        resolve({
          pageArea: detail,
          prizeAreas: prizeAreas.value,
          voteConfigEntity: voteConfigEntity,
        });
      } else {
        formRef.value.scrollToField(Object.keys(invalidFields)[0]);
        reject(`请检查${form.value.name}`);
      }
    });
  });
};

// 投票参数校验
const checkConfig = (): any => {
  return new Promise((resolve, reject) => {
    voteRef.value.validate(async (valid: any) => {
      if (valid) {
        let detail: any = deepClone(voteConfig.value);
        detail.voteStart = detail.voteTime[0];
        detail.voteEnd = detail.voteTime[1];
        detail.rewardList.forEach((item: any) => {
          if (item.lotteryAreaUid) item.lotteryArea = "";
          if (item.prizeAreaUid) item.prizeArea = "";
          if (item.prizeUid) item.prizeId = "";
          if (item.prizeSpecUid) item.prizeSpec = "";
          if (item.ticketAct === "local") item.ticketAct = "";
        });
        resolve(detail);
      } else reject(`请检查${form.value.name}`);
    });
  });
};

defineExpose({ submit, refresh: formatData });
</script>
<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    :disabled="activityReadonly"
    label-width="auto"
  >
    <!-- 中奖限制 -->
    <template v-if="showPrizePool">
      <h3 class="collpase-title">中奖限制</h3>
      <el-form-item label="中奖总次数：" prop="lotteryTotalLimit">
        <el-radio-group v-model="form.lotteryTotalLimit">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
        <template v-if="form.lotteryTotalLimit == 1">
          <el-form-item label-width="10px" prop="lotteryTotalNum">
            <EasyNumberInput
              v-model="form.lotteryTotalNum"
              :min="1"
              :max="9999"
              :precision="0"
              unit="次"
            />
          </el-form-item>
        </template>
      </el-form-item>
      <el-form-item label="中奖次数：">
        <el-radio-group v-model="form.lotteryLimitType">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">限制</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.lotteryLimitType == 1">
        <div class="flex-contain" v-for="(limit, index) in form.lotteryLimit">
          每人&nbsp;&nbsp;
          <el-select
            v-model="limit.type"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option
              v-for="(item, key) in frequencyType"
              :label="item"
              :value="Number(key)"
            /> </el-select
          >&nbsp;&nbsp; 最多
          <el-form-item
            label-width="10px"
            :prop="`lotteryLimit.${index}.limitNum`"
            :rules="[
              { required: true, message: '请填写限制次数', trigger: 'blur' },
            ]"
          >
            <EasyNumberInput
              v-model="limit.limitNum"
              :min="1"
              :max="9999"
              unit="次"
              :precision="0"
            ></EasyNumberInput>
          </el-form-item>
        </div>
      </el-form-item>
    </template>
  </el-form>
  <el-form
    ref="voteRef"
    :model="voteConfig"
    :rules="rules"
    label-width="auto"
    :disabled="activityReadonly"
  >
    <h3 class="collpase-title">投票配置</h3>
    <el-form-item label="投票时间：" prop="voteTime" style="width: 500px">
      <el-date-picker
        v-model="voteConfig.voteTime"
        type="datetimerange"
        value-format="x"
        range-separator="~"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
      />
    </el-form-item>
    <el-form-item label="投票规则：" prop="voteRule">
      <el-radio-group v-model="voteConfig.voteRule">
        <el-radio :label="0">每日均可投票</el-radio>
        <el-radio :label="1">一次性投票</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      用户{{ voteConfig.voteRule == 0 ? "每天" : "" }}可投<el-form-item
        label-width="10px"
        prop="voteChance"
      >
        <EasyNumberInput
          v-model="voteConfig.voteChance"
          :min="1"
          :max="9999"
          :precision="0"
          unit="票"
          style="width: 150px"
          @change="updateData"
        />
      </el-form-item>
      &nbsp;&nbsp;，同一作品最多可投<el-form-item
        label-width="10px"
        prop="duplicateChance"
      >
        <EasyNumberInput
          v-model="voteConfig.duplicateChance"
          :min="1"
          :max="9999"
          :precision="0"
          unit="票"
          style="width: 150px"
          @change="updateData"
        />
      </el-form-item>
    </el-form-item>
    <el-form-item label="投票成功奖励：">
      <el-form-item label-width="0" prop="rewardType" style="width: 120px">
        <el-select v-model="voteConfig.rewardType" placeholder="请选择">
          <el-option label="首次投票" :value="0" />
          <el-option label="每次投票" :value="1" />
        </el-select> </el-form-item
      >&nbsp;&nbsp;获得
      <el-form-item
        label-width="10px"
        v-for="(reward, rIndex) in voteConfig.rewardList"
      >
        <RewardSelector
          v-model="voteConfig.rewardList[rIndex]"
          :subType="form.subType"
          lottery
          :prizeAreas="prizeAreas"
          :prefix="`rewardList.${rIndex}.`"
          @change="updateData"
          @addPool="addPool"
          @addPrize="addPoolPrize"
        />
      </el-form-item>
    </el-form-item>
  </el-form>
  <PrizePool
    ref="poolRef"
    v-model="prizeAreas"
    :poolType="showPrizePool ? [1, 2] : [2]"
    :poolBaseInfo="prizePoolType"
    :pageFlag="form.pageFlag"
    :quote="quotePrize"
    @change="updateData"
  ></PrizePool>
</template>
<style lang="scss" scoped>
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;
  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

.flex-contain {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
</style>
